package mahjong;

import java.util.*;

/**MonteCarlo player
 * AI player that can simulate moves in order to solve the board 
 *
 */
public class MonteCarloPlayer extends AIPlayer
{
	private LinkedList<Tile[]> solution;

	public void init(Board b)
	{
		board = b;
		solution = null;
		int i = 0;
		while (i <= 1000 && solution == null) {
			monteCarlo();
			i++;
		}
	}

	/**
	 * Implementation of the chooseMove. which chooses a move
	 * from all available moves
	 */
	public Tile[] chooseMove()
	{
		if (solution == null) {
			ArrayList<Tile[]> aMoves = board.getAvailableMoves();
			return aMoves.get((int) Math.random() * (aMoves.size() + 1));		
		} else {
			return solution.remove();
		}
	}
	/**
	 * Runs the random player a number of times until
	 * a valid solution is found
	 */
	private void monteCarlo()
	{
		ArrayList<Tile[]> moves;
		Tile[] move;
		Random r = new Random();

		solution = new LinkedList<Tile[]>();
		while (!board.isEmpty() && !board.isDeadLock()) {
			moves = board.getAvailableMoves();
			move = moves.get((int) r.nextInt(moves.size()));
			solution.add(move);
			move[0].removeFromPlay();
			move[1].removeFromPlay();
		}

		
		if (board.isDeadLock()) 
		{
			for (Tile[] m : solution) {
				m[0].addToPlay();
				m[1].addToPlay();
			}
			solution = null;
		}
		else
		{
			for (Tile[] m : solution) {
				m[0].addToPlay();
				m[1].addToPlay();
			}
		}
		

	}
}
